<template>
    <div class="warp-2" style="height: 100%;">
        <navbar :title="freshDetail.itmTitle" v-show="isShowNav && $store.state.config.iosHeaderShow"></navbar>
        <!-- 当隐藏了下方的:取消报名按钮就设置"56px 0 0" -->
        <div class="content" :style="{padding:!isShowNav? '0' : (!signUpBtn && freshDetail.appId && freshDetail.learnerStatus !== 'F' && freshDetail.learnerStatus !== 'W') ? '56px 0 0' : '56px 0 57px'}">
            <van-pull-refresh v-model="isLoading" @refresh="onPulldownTop" loading-text="loading" pulling-text="" loosing-text="">
                <div class="view-body body-content" v-if="freshDetail">
                    <div style="position: relative;">
                        <img :src="freshDetail.itmIcon ? appUrl + freshDetail.itmIcon : ''" alt="" style="width: 100%;height:211px;display: block;"/>
                    </div>
                    <div>
                        <div class="white-bg module-box-19">
                            <p>
                                {{ freshDetail.itmTitle }}
                            </p>
                            <div class="font-size12 color999" style="padding-top: 10px;">
                                <span>{{ $t("teaching") }}&nbsp;&nbsp;&nbsp;{{freshDetail.teacher}}</span>
                            </div>
                            <div class="font-size12 color999" style="padding-top: 10px;">
                                <div style="display: flex;align-items: center;">
                                    <span>{{ $t('cos_inprogress_name') }}</span>
                                    <div class="progress-box">
                                        <van-progress :percentage="freshDetail.progress ? freshDetail.progress : 0"
                                            color="#70B603" :show-pivot="false" track-color="#F2F2F2"/>
                                    </div>
                                    <span style="color:#333333">{{freshDetail.progress ? freshDetail.progress : 0}}%</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="content-list">
                        <h3 class="white-bg" style="padding: 15px 15px;border-bottom: 1px solid #eee;">{{ $t('Learning_content') }}</h3>
                        <!--您未申请报名-->
                        <div class="box-table white-bg" style="width:100%;height: 300px;" v-if="freshData && !unregistered  ">
                            <div class="box-table-cell" style="text-align: center;">
                                <div class="no-data" style="margin-top: -50px;">
                                    <img src="../../../static/images/no-data.png" alt=""/>
                                    <p class="color999">{{ promptOne }}</p>
                                    <p class="color999">{{ promptTwo }}</p>
                                </div>
                            </div>
                        </div>
                        <!--报名成功后，没有内容-->
                        <div class="box-table white-bg" style="width:100%;height: 300px;" v-if="freshData && !isIntegrated && ((unregistered && (!freshCourseItems || freshCourseItems.length <= 0)))">
                            <div class="box-table-cell" style="text-align: center;">
                                <div class="no-data">
                                    <img src="../../../static/images/no-data.png" alt=""/>
                                    <p class="color999">{{ $t("no_data") }}</p>
                                </div>
                            </div>
                        </div>
                        <!--报名成功后，有内容，跳到网上课程-->
                        <ul class="conent-list" v-if="freshData && unregistered  && (freshCourseItems && freshCourseItems.length > 0) && !isIntegrated">
                            <li class="white-bg" v-for="(content,index) in freshCourseItems" :key="index">
                                <p v-if="content.nodeType < 1 && content.childList && content.childList.length > 0" class="word-title-02 paddingLR15 clearfix" @click="unfoldModule(index)"><span class="word-clamp-1">{{ content.nodeTitle }}</span><i class="more-icon" :class="{'cur' : moreCourse != false && index == clickindex}"></i></p>
                                <!--有模块夹-->
                                <div class="module-box-20" v-if="content.nodeType < 1 && moreCourse" v-show="index == clickindex">
                                    <template v-if="content.childList && content.childList.length > 0">
                                    <div class="box" v-for="(listInfo,index) in content.childList" :key="index">
                                        <!--  :studyFaceInd='studyFaceInd' @vodClick='vodClick' :confirmIs='confirmIs' -->
                                        <information-module :list="listInfo" :unregistered="unregistered" :tkhId="freshData.appTkhId" :itmId="freshData.itmId" :resId="freshData.resId" :userEntId="userEntId"></information-module>
                                        <div class="border-bottom2"></div>
                                    </div>
                                    </template>
                                </div>
                                <!--没有模块夹-->
                                <div class="module-box-20" v-if="content.nodeType === 1">
                                    <div class="box">
                                        <!--  :studyFaceInd='studyFaceInd' @vodClick='vodClick' :confirmIs='confirmIs' -->
                                        <information-module :list="content" :unregistered="unregistered" :tkhId="freshData.appTkhId" :itmId="freshData.itmId" :resId="freshData.resId" :userEntId="userEntId"></information-module>
                                    </div>
                                </div>
                            </li>
                        </ul>
                        <!--报名成功后，有内容，跳转到项目式课程-->
                        <div v-if="isIntegrated && unregistered && integratedContent == true">
                            <integrated-module></integrated-module>
                        </div>
                    </div>
                </div>
            </van-pull-refresh>
            <!-- 报名按钮 -->
            <div class="sign-up-content" v-if="!(!signUpBtn && freshDetail.appId && freshDetail.learnerStatus !== 'F' && freshDetail.learnerStatus !== 'W')">
                <!--我要报名-->
                <template v-if="signUpBtn">
                    <div class="sign-up" @click.once="enrol">
                        {{ $t('Start_learning') }}
                    </div>
                </template>
                <!--取消报名-->
                <!-- <div class="sign-up-cancel" v-else-if="!signUpBtn && freshDetail.appId && freshDetail.learnerStatus !== 'F' && freshDetail.learnerStatus !== 'W'">
                    <div @click.once="cancelEnrol">
                        {{ $t('Cancel_learning') }}
                    </div>
                </div> -->
                <!-- 已完成学习 -->
                <div class="sign-up-cancel" v-else-if="!signUpBtn && freshDetail.learnerStatus === 'C'">
                    <div>
                        {{ $t('cos_app_completed') }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import InformationModule from '@/components/certifiedCourse/InformationModule';
import IntegratedModule from '@/components/certifiedCourse/Integrated';
import { Button, Toast } from 'vant';
export default {
    name: 'course-contents',
    components: {
        InformationModule,
        IntegratedModule,
        [Button.name]: Button,
        vanToast: Toast
    },
    data() {
        return {
            modId: '',
            confirmIs: false,
            tips: false,
            errorTips: false,
            examDetail: '',
            course: {},
            item: {}, //课程基本信息
            app: {}, //学员报名信息
            courseEvaluation: {}, //课程学习记录
            cosContent: {}, //网上内容
            btnNum: '', //该属性是旧的逻辑用于控制一些按钮（如报名按钮）显示的标记
            result: 'notapp', //报名结果
            unregistered: false, //未报名1，等待队列与等待审批也算报名成功
            unregisteredTwo: false, //未报名2，等待队列与等待审批不算报名成功
            promptOne: '', //第一句提示语
            promptTwo: '', //第二句提示语
            moreCourse: false, //模块里的课程
            clickindex: '', //展开模块课程的点击index
            integratedContent: false, //项目式培训有没有内容
            /*新的参数*/
            freshCourseItems: [], // 课程课件集合
            freshData: {}, // 课程内容详情
            applyStatus: '', //报名状态 icw.....和是否为空
            ofApproval: false, // 报名是否需要审核
            userEntId: window.localStorage.getItem('loginUser'),
            isIntegrated: false,
            freshDetail: {}, // 课程详情
            isNoRead: false, // 课程公告是否含有未阅读的公告
            fId: this.$route.query.fId, // 父课程id
            isLoading: false,
            signUpBtn: false //报名按钮
        };
    },
    computed: {
        cont() {
            return this.$store.getters.getUnregistered;
        },
        isShowNav() {
            return this.$store.getters.getIsShowNav;
        }
    },
    methods: {
        setContent(data) {
            this.course = data;
            this.btnNum = this.course.btn; //该属性是旧的逻辑用于控制一些按钮（如报名按钮）显示的标记
            this.item = this.course.item; //课程基本信息
            this.app = data.app || {}; //学员报名信息
            this.freshData = data;
            this.applyStatus = data.learnerStatus;
            this.freshCourseItems = data.contentList;
            this.unregistered = this.$store.getters.hasApped(this.applyStatus);
            if (data.courseEnum === 'OPEN_COURSE') {
                this.unregistered = true;
            }
            this.unregisteredTwo = this.$store.getters.hasAppPassed(this.applyStatus);
            this.getContentTipInfo(this.unregistered, data.isApproval);
            this.courseEvaluation = this.course.courseEvaluation; //课程学习记录    I C 这些
            this.appStatus = this.getAppStatus(data.app, this.courseEvaluation); //报名学状态
            /*判断项目式培训有没有内容*/
            if (this.isIntegrated === true) {
                if (this.course.integratedCourseModuleDTO && Object.keys(this.course.integratedCourseModuleDTO).length === 0) {
                    this.integratedContent = false; //没有内容
                } else {
                    this.integratedContent = true; //有内容
                }
            }
        },
        subTime(value) { //yyyy-MM-dd HH:mm
            if (value) {
                return value.substring(0, value.indexOf(':', value.indexOf(':') + 1));
            } else {
                return value;
            }
        },
        getContentTipInfo(unregistered, applyStatus) { // 现在报名只有是否需要审批
            let _this = this.$root;
            let btnNum = 1;
            if (applyStatus) {
                btnNum = 4;
            }
            if (!unregistered) { //还没报名
                switch (btnNum) {
                case 1:
                    this.promptOne = _this.$t('cos_content_click_to_apply'); //您未申请报名 报名成功后才能开始学习
                    this.promptTwo = _this.$t('cos_content_click_to_begin');
                    break;
                case 4 : //未报名，但该课程是需要报名审批通过后才能学习的情况
                    this.promptOne = _this.$t('cos_content_apply_tip_1'); //该课程需要先提交报名申请,等待管理员或上司审批通过才能开始学习
                    this.promptTwo = _this.$t('cos_content_apply_tip_2');
                    break;
                }
            }
        },
        /**
         *判断是否已报名
         * @param app 学员报名信息
         * @param courseEvaluation 课程学习记录
         * @returns {string}
         */
        getAppStatus(app, courseEvaluation) {
            var result = 'notapp';//默认未报名
            if (courseEvaluation && courseEvaluation.cov_status) {
                result = courseEvaluation.cov_status;
            } else if (app) {
                result = app.app_status;
            }
            return result;
        },
        unfoldModule(index) { //展开模块里的课程
            this.moreCourse = !this.moreCourse;
            this.clickindex = index;
        },
        /**
         * 获取课程详情 */
        getFreshDetail() {
            this.isLoading = true;
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/detail`,
                params: {
                    itmId: this.$route.params.itmId,
                    mobileInd: 1
                }
            }).then(async res => {
                if (res && res.status === 200) {
                    //是否报名字段判断
                    await this.checkApply(res.data.app, res.data.appTkhId, res.data.appApprovalStatus);
                    this.freshDetail = res.data;
                    this.isLoading = false;
                    this.app = res.data.app;
                    if (res.data.courseEnum === 'INTEGRATED_COURSE') {
                        this.isIntegrated = true;
                    } else {
                        this.isIntegrated = false;
                    }
                    this.setContent(res.data);
                }
            });
        },
        onPulldownTop() {
            setTimeout(() => {
                // this.selectType(0);
                this.course = {};
                this.item = {}; //课程基本信息
                this.getFreshDetail();
            }, 900);
        },
        /**
         * 公告是否含有未阅读 */
        getIsRead() {
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/itmMessageIsRead`,
                params: {
                    itmId: this.fId
                }
            }).then((res) => {
                this.isNoRead = res.data;
            });
        },
        /*报名-原产品逻辑*/
        enrol(isApproval = false) {
            if (this.signUpBtn || isApproval) { //报名
                this.$axios({
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8'
                    },
                    url: `/app/api/trainee/course/sign-in`,
                    data: this.$route.params.itmId
                }).then(res => {
                    //403 不允许重读  // 402 名额已满  // 403 不可重读 // 401 非目标学员不允许报名
                    if (res.data && res.data.keyList && res.data.keyList.length > 0) { //有先修课程
                        let title = '';
                        res.data.keyList.forEach((v, index) => {
                            title += (index + 1) + '.' + v + '';
                        });
                        Toast(this.$t('following_prerequisite_courses', {'value': title}));
                        return false;
                    }
                    this.getFreshDetail();
                    Toast(this.$t('enroll_success'));
                }).catch(err => {
                    let msg = err.response.data.errCode;
                    switch (msg) {
                    case 'ERROR_BEFORE_APPLICATION_TIME':
                        msg = this.$t('cos_sign_up_not_permitted_1');
                        break;
                    case 'ERROR_AFTER_APPLICATION_TIME':
                        msg = this.$t('cos_sign_up_not_permitted_2');
                        break;
                    default:
                        msg = err.response.data.errMsg;
                    }
                    Toast(msg);
                });
            }
        },
        //判断显示报名按钮规则
        checkApply(app, appThkId, approvalStatus) {
            if (app && app.appStatus === 'Rejected') {
                this.signUpBtn = true;
            } else if (approvalStatus === 'PENDING') {
                this.signUpBtn = false;
            } else {
                this.signUpBtn = appThkId === null;
            }
        },
        /**
         * 取消报名-原产品逻辑
         */
        cancelEnrol() {
            if (!this.signUpBtn && !this.freshDetail.isLearnerModule) {
                this.$axios({
                    method: 'DELETE',
                    url: `/app/api/trainee/course/sign-in`,
                    params: {appId: this.freshDetail.appId}
                }).then(res => {
                    this.getFreshDetail();
                    Toast(this.$t('delete_enroll'));
                }).catch((error) => {
                    if (error) {
                        Toast(this.$t(error.response.data.errMsg));
                    }
                });
            } else {
                Toast(this.$t('cos_tips_1'));
            }
        }
    },
    mounted() {
        setTimeout(() => {
            this.getFreshDetail();
        }, 1000);
        this.getIsRead();
    }
};
</script>

<style scoped lang="less">
    @import "./courseLess.less";
    .word-title-02 {
        height: 60px;
        line-height: 60px;
        background: #fafafa;
        span {
            float: left;
            width: calc(100% - 26px);
        }
    }
    .more-icon {
        background-size: 13px;
        background-position: -2px 0;
        margin-top: 20px;
    }
    .more-icon.cur {
        width: 16px;
        background-position: 0 -20px;
    }
    .conent-list {
        li {
            border-bottom: 1px solid #e6e6e6;
            &:nth-last-child(1) {
                border-bottom: none;
            }
        }
    }
    .tips-box {
        display: flex;
        align-items: center;
    }
  h2::before{
    content: '';
    width: 5px;
    height: 15px;
    border-radius: 10px;
    display: inline-block;
    background-color: #003764;
    margin-right: 11px;
    margin-bottom: -2px;
  }
  .module-box-19 {
        padding: 15px;
        .title-play-tour{
          line-height: 20px;
          font-size: 22px;
          color: #666;
          padding-top: 5px;
        }
        p {
            font-weight: bold;
            font-size: 18px;
        }
        .word-title-09 {
            margin-right: 10px;
            height: 18px;
            line-height: 19px;
            display: inline-block;
        }
    }
    .progress-box{
        width: 120px;
        margin: 0 10px;
    }
    .message-2{
        width: 45px;
        height: 56px;
        display: flex;
        justify-content: center;
        align-items: center;
        &:before{
            content: '';
            display: block;
            width: 21px;
            height: 21px;
            background: url(./images/bell.png) no-repeat 0 0;
            background-size: 20px;
        }
    }
    .dot{
        position: absolute;
        background: red;
        width: 8px;
        height: 8px;
        border: 1px solid #fff;
        border-radius: 50%;
        top: 15px;
        right: 13px;
    }
    .content-list{
        margin-top: 10px
    }
    // 报名
    .sign-up-content{
        display: flex;
        height: 56px;
        border-top: 1px solid #cccccc;
        justify-content: center;
        align-content: center;
        align-items: center;
        position: absolute;
        width: 100%;
        z-index: 1;
        background: #fff;
        padding: 0 40px;
        box-sizing: border-box;
        .sign-up{
            // width: 80%;
            flex: 1;
            height: 40px;
            text-align: center;
            line-height: 40px;
            background: #075ebb;
            color: #ffffff;
            border-radius: 4px;
            &.cur{
                background: #E6E6E6;
                color: #cccccc;
            }
        }
        .sign-up-cancel{
            width: 80%;
            height: 40px;
            text-align: center;
            line-height: 40px;
            background: #075ebb;
            border-radius: 20px;
            color:#fff;
        }
    }
</style>
